package cn.pzaily.orange.manage.security;

import cn.pzaily.orange.core.utils.ObjectUtils;
import cn.pzaily.orange.manage.model.SysUser;
import cn.pzaily.orange.manage.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @PackageName: cn.pzaily.orange.manage.security
 * @Description:
 * @Author: Pang
 * @Date: 2021-05-12 21:10
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userServer;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser user = userServer.findByUserName(s);
        if (ObjectUtils.isNull(user)) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        Set<String> permissions = userServer.findPermissionsByUserName(user.getName());
        List<GrantedAuthority> grantedAuthorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        return new UserDetailsImpl(user.getName(), user.getPassword(), user.getSalt(), grantedAuthorities);
    }
}
